<script setup>
import { ref } from 'vue'
import { sendRegister,checkCode } from '../api/userToService'
import { useRouter } from 'vue-router'
import {useCounterStore} from '../stores/counter'

const router = useRouter()
const counterStore = useCounterStore()
// 添加表单引用
const formData = ref({
  username: '',
  password: '',
  phone: ''
})

const code = ref('')
const rules = ref({
  username: [
    { required: true, message: 'please input your name', trigger: 'blur' },
    { min: 3, max: 20, message: 'name length must be 3-20', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'please input your password', trigger: 'blur' },
    { min: 3, max: 20, message: 'password length must be 3-20', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: 'please input your phone number', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: 'please input correct phone number', trigger: 'blur' }
  ]
})

// 添加表单引用
const passcodeTime = ref(10)
const isPasscodeDisabled = ref(false)
const formRef = ref(null)
const toLogin = () => {
  router.go(-1)
}
const changePasscode = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('please input correct information')
      return
    }

    let timer = null  // 在外部定义 timer
    try {
      isPasscodeDisabled.value = true  // 先禁用按钮
      timer = setInterval(() => {
        passcodeTime.value--
        if (passcodeTime.value === 0) {
          clearInterval(timer)
          isPasscodeDisabled.value = false
          passcodeTime.value = 10
        }
      }, 1000)
      const res = await sendRegister(formData.value);
      //请求成功处理
      if (res.statuCode === 200) {
        ElMessage.success(res.message)
        counterStore.codeCheck = res.result
        code.value.username = res.result.username
      }
      //该用户
      else if (res.statuCode === 201) {
        ElMessage.error(res.message)
        router.push('/')
      }
      //有该用户名占用注册池
      else if (res.statuCode === 202) {
        ElMessage.error(res.message)
      }
    } catch (error) {
      //请求异常处理
      clearInterval(timer)  // 清除计时器
      isPasscodeDisabled.value = false
      passcodeTime.value = 10
    }
  })
}
const toGetCheckCodeBox = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('please input correct information')
      return
    }
    ElMessageBox.prompt('please input your code', 'To check code', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      inputPattern: /^\d{6}$/,
      inputErrorMessage: 'Please input correct code'
    }).then(async ({ value }) => {
      code.value = value
      console.log(code.value)
      const res = await checkCode({
          checkCodeEntity: counterStore.codeCheck,
          code: code.value
      })
      if(res.statuCode === 200){
        ElMessage.success(res.message)
        router.push('/')
      }else if(res.statuCode === 401 || res.statuCode === 402){
        ElMessage.error(res.message)
      }

    })

  })

}

</script>
<template>
  <el-container>
    <el-header>
      <div class="header animate__animated animate__backInDown ">
        <div class=" animate__animated  animate__headShake animate__delay-3s animate__infinite "
          style="color: #09A8AD; text-shadow: 10px 10px rgb(1, 1,1,0.6);"> WELCOME TO ME</div>
      </div>
    </el-header>

    <el-main style="display: flex;justify-content: center;align-items: center;height: 900px;opacity: 0.9;">
      <div class="reginBody animate__animated  animate__backInUp"
        style="display: flex;justify-content: center;align-items: center;flex-direction: column;">
        <el-form :model="formData" :rules="rules"
          style="z-index: 1;display: flex;flex-direction: column;justify-content: center;align-items: center;"
          ref="formRef" status-icon>
          <el-form-item label="Activity name" label-position="top" prop="username">
            <el-input placeholder="input your name" v-model="formData.username" />
          </el-form-item>
          <el-form-item label="Activity password" label-position="top" prop="password">
            <el-input placeholder="input your password" v-model="formData.password" />
          </el-form-item>
          <el-form-item label="Activity phone number" label-position="top" prop="phone">
            <el-input v-model="formData.phone" placeholder="input your phone number" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" ref="passcodeRef" :disabled="isPasscodeDisabled" @click="changePasscode"
              size="large">
              <div v-if="!isPasscodeDisabled">send passcode</div>
              <div v-else>after {{ passcodeTime }} seconds you can send passcode</div>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toGetCheckCodeBox" size="large">to check code</el-button>
          </el-form-item>
        </el-form>
        <div style="position: absolute;bottom: 10%;left: 10%;z-index: 1;">
          <el-link @click="toLogin" style="font-size: large;" type="primary">Login</el-link>
        </div>
      </div>
    </el-main>



  </el-container>
</template>



<style scoped>
@import url('../assets/css/Regin.css');
</style>
